#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct ListNode {
    int val;
    struct ListNode* next;
};
struct ListNode* detectCycle(struct ListNode* head) {
    struct ListNode* cur, * slow, * fast;
    cur = slow = fast = head;
    while (cur)
    {
        while (slow && fast->next)
        {
            if (slow->next == cur)
            {
                return slow;
            }
            else
            {
                slow = slow->next;
                if(fast->next->next)
                   fast = fast->next->next;
            }
            if (slow == fast)
            {
                cur = cur->next;
                break;
            }
        }
        if (slow == NULL || fast->next == NULL)
        {
            return NULL;
        }
    }
    return NULL;
}

int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n1->val = 3;
   
    n2->val = 2;
    n3->val = 0;
    n4->val = 1;
    n5->val = 4;
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n2;

    detectCycle(n1);

    return 0;
}